package com.movitech.mobile.ddzy.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.HeadersUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.sessionuser.SessionMenuVo;
import com.movitech.mobile.cz.base.sessionuser.SessionUserService;
import com.movitech.mobile.cz.base.sessionuser.SessionUserVo;
import com.movitech.mobile.cz.base.sys.entity.SCompany;
import com.movitech.mobile.cz.base.sys.entity.SRegionalCompany;
import com.movitech.mobile.cz.base.sys.service.SCompanyService;
import com.movitech.mobile.cz.base.sys.service.SProjectService;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.ddzy.bpm.feignclient.MbsDataAuthClient;

@Service("extSessionUserService")
public class SessionUserServiceImpl implements SessionUserService {

    @Value("${api.feign.auth.appuuid}")
    private String apiFeignAuthAppuid;

    @Autowired
    @Qualifier("sRegionalCompanyService")
    private SRegionalCompanyService sRegionalCompanyService;

    @Autowired
    @Qualifier("sProjectService")
    private SProjectService sProjectService;

    @Autowired
    @Qualifier("sCompanyService")
    private SCompanyService sCompanyService;

    @Autowired
    MbsDataAuthClient mbsDataAuthClient;

    @Override
    public SessionUserVo getSessionUser() {

        SessionUserVo userVo = null;
        try {
            Gson gson = new Gson();
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            HttpSession session = request.getSession();
            Object userJson = session.getAttribute("userJson");
            if (userJson != null) {
                userVo = gson.fromJson(userJson.toString(), new TypeToken<SessionUserVo>() {
                }.getType());
                if (userVo != null) {
                    if (StringUtils.isNotEmpty(userVo.getCompanyCode())) {
                        List<SCompany> lstSCompany = sCompanyService.getSCompanyByCodeAndRegionalCompanyId(userVo.getCompanyCode(), null);
                        if (CollectionUtils.isNotEmpty(lstSCompany)) {
                            SCompany sCompany = lstSCompany.get(0);
                            userVo.setsCompanyId(sCompany.getId());
                            userVo.setsCompanyName(sCompany.getCompanyName());

                            //
                            if (StringUtils.isNotEmpty(sCompany.getRegionalCompanyId())) {
                                SRegionalCompany sRegionalCompany = sRegionalCompanyService.selectById(sCompany.getRegionalCompanyId());
                                if (sRegionalCompany != null) {
                                    userVo.setsRegionalCompanyName(sRegionalCompany.getRegionalCompanyName());
                                    userVo.setsRegionalCompanyId(sRegionalCompany.getId());
                                    if (sRegionalCompany.getRcType() == null) {
                                        userVo.setGroupFlag(CommonConstants.NO_INTEGER);
                                    } else {
                                        if (sRegionalCompany.getRcType() == 1) {//类型（1：集团，2：地区公司）
                                            userVo.setGroupFlag(CommonConstants.YES_INTEGER);
                                        } else {
                                            userVo.setGroupFlag(CommonConstants.NO_INTEGER);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        return userVo;
    }

    /**
     * 从其它系统跳转到本系统无权限的问题,现解决方案如下
     * 1.从其它系统跳转时带上参数initauth=y
     * 2.程序接收到带此参数的地址后,使用getUserAndAuthByToken进行token验证,此controller有两个参数,token和authAppUUIDQX
     * 3.此controller会初始化权限
     *
     * @param request
     * @return
     */
    @Override
    public SessionUserVo getSessionUserByToken(HttpServletRequest request) {
        SessionUserVo sessionUserVo = null;
        String token = HeadersUtils.getHeadByKey(request, "token");
        String initauth = HeadersUtils.getHeadByKey(request, "initauth");//initauth=y
        sessionUserVo = getUserByToken(token, initauth);
        return sessionUserVo;
    }

    public SessionUserVo getUserByToken(String token, String initauth) {
        LicenseUtil.INSTANCE.validate();
        SessionUserVo sessionUserVo = null;
        RestReturnResult<SessionUserVo> restReturnResult = null;
        if (StringUtils.isNotEmpty(token)) {
            try {
                String userJson = "";
                Gson gson = new Gson();
                if (StringUtils.equalsIgnoreCase(initauth, "y")) {//在别的系统跳
                    userJson = mbsDataAuthClient.getUserAndAuthByToken(token, apiFeignAuthAppuid);
                } else {//一般使用
                    userJson = mbsDataAuthClient.getUserByToken(token);
                }
                System.out.println("=====getUserByToken======" + userJson);
                if (StringUtils.isNotEmpty(userJson)) {
                    JSONObject jsonObject = JSON.parseObject(userJson);
                    JSONObject user = JSON.parseObject(jsonObject.getString("data"));
                    sessionUserVo = user.toJavaObject(SessionUserVo.class);
//					restReturnResult = gson.fromJson(jsonObject.toJSONString(), new TypeToken<RestReturnResult<SessionUserVo>>(){}.getType());
                    if (sessionUserVo != null) {
//						sessionUserVo = restReturnResult.getData();
                        if (sessionUserVo != null) {
                            if (StringUtils.isNotEmpty(sessionUserVo.getCompanyCode())) {
                                List<SCompany> lstSCompany = sCompanyService.getSCompanyByCodeAndRegionalCompanyId(sessionUserVo.getCompanyCode(), null);
                                if (CollectionUtils.isNotEmpty(lstSCompany)) {
                                    SCompany sCompany = lstSCompany.get(0);
                                    sessionUserVo.setsCompanyId(sCompany.getId());
                                    sessionUserVo.setsCompanyName(sCompany.getCompanyName());
                                    //
                                    if (StringUtils.isNotEmpty(sCompany.getRegionalCompanyId())) {
                                        SRegionalCompany sRegionalCompany = sRegionalCompanyService.selectById(sCompany.getRegionalCompanyId());
                                        if (sRegionalCompany != null) {
                                            sessionUserVo.setsRegionalCompanyName(sRegionalCompany.getRegionalCompanyName());
                                            sessionUserVo.setsRegionalCompanyId(sRegionalCompany.getId());
                                            if (sRegionalCompany.getRcType() == null) {
                                                sessionUserVo.setGroupFlag(CommonConstants.NO_INTEGER);
                                            } else {
                                                if (sRegionalCompany.getRcType() == 1) {//类型（1：集团，2：地区公司）
                                                    sessionUserVo.setGroupFlag(CommonConstants.YES_INTEGER);
                                                } else {
                                                    sessionUserVo.setGroupFlag(CommonConstants.NO_INTEGER);
                                                }
                                            }
                                        }else{
                                            sessionUserVo.setGroupFlag(CommonConstants.NO_INTEGER);
                                        }
                                    }else{

                                        sessionUserVo.setGroupFlag(CommonConstants.NO_INTEGER);
                                    }
                                }else{
                                    sessionUserVo.setGroupFlag(CommonConstants.NO_INTEGER);
                                }
                            }else{
                                sessionUserVo.setGroupFlag(CommonConstants.NO_INTEGER);
                            }

                            sessionUserVo = getUserDataAuth(sessionUserVo);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sessionUserVo;
    }


    /**
     * 额外数据权限
     */
    private SessionUserVo getUserDataAuth(SessionUserVo sessionUserVo) {
        LicenseUtil.INSTANCE.validate();
        RestReturnResult<String> restReturnResult = null;
        String dataAuthJson = "";
        Gson gson = new Gson();
        List<String> lstAllCompanyCode = new ArrayList<String>();
        if (StringUtils.isNotEmpty(sessionUserVo.getCompanyCode())) {
            lstAllCompanyCode.addAll(StringUtils.getListBySplitStr(sessionUserVo.getCompanyCode()));
        }
        dataAuthJson = mbsDataAuthClient.getDataAuth(sessionUserVo.getEmployeeID());

        try {
            System.out.println("===数据权限===" + dataAuthJson);
            JSONObject jsonObject = JSON.parseObject(dataAuthJson);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotEmpty(dataAuthJson) && StringUtils.isNotEmpty(data)) {
                restReturnResult = gson.fromJson(dataAuthJson.toString(), new TypeToken<RestReturnResult<String>>() {
                }.getType());
                if (restReturnResult != null) {
                    String lstCompanyCode = restReturnResult.getData();
                    if (StringUtils.isNotEmpty(lstCompanyCode)) {
                        String[] comCodeS = lstCompanyCode.split(",");
                        for (String item : comCodeS) {
                            if (StringUtils.isNotEmpty(item)) {
                                lstAllCompanyCode.add(StringUtils.replace(item, "CGXT_", "").trim());
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        ///地区公司汇总
        List<String> lstSRegionalCompanyId = new ArrayList<String>();
        List<String> lstSRegionalCompanyName = new ArrayList<String>();
        if (CollectionUtils.isNotEmpty(lstAllCompanyCode)) {
            List<SCompany> lstSCompany = sCompanyService.getSCompanyListByCodes(lstAllCompanyCode);
            for (SCompany sCompany : lstSCompany) {
                if (StringUtils.isNotEmpty(sCompany.getRegionalCompanyId())) {
                    if (StringUtils.isListContainString(lstSRegionalCompanyId, sCompany.getRegionalCompanyId())) {
                        continue;
                    }

                    ////
                    SRegionalCompany sRegionalCompany = sRegionalCompanyService.selectById(sCompany.getRegionalCompanyId());
                    if (sRegionalCompany != null) {
                        lstSRegionalCompanyId.add(sRegionalCompany.getId());
                        lstSRegionalCompanyName.add(sRegionalCompany.getRegionalCompanyName());

                        if (sRegionalCompany.getRcType() == 1) {//类型（1：集团，2：地区公司）
                            sessionUserVo.setGroupFlag(CommonConstants.YES_INTEGER);
                        }
                    }
                }
            }
        }
        sessionUserVo.setLstSRegionalCompanyId(lstSRegionalCompanyId);
        sessionUserVo.setLstSRegionalCompanyName(lstSRegionalCompanyName);

        return sessionUserVo;
    }
}
